package com.aaa.controller;

import cn.hutool.db.Entity;
import com.aaa.service.UserService;
import com.aaa.service.impl.UserServiceImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author ：Teacher陈（86521760@qq.com）
 * @date ：Created in 2024/7/16 14:35
 * @description：用户业务控制器
 * @modified By：
 * @version: 1.0
 */
@WebServlet("/user")
public class UserController extends HttpServlet {
    UserService userService = new UserServiceImpl();


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求和响应的编码格式
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        //获取请求参数，并且保存在map集合中
        Map map = new HashMap();
        Enumeration<String> parameterNames = req.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String parameterName = parameterNames.nextElement();
            String parameterValue = req.getParameter(parameterName);
            map.put(parameterName, parameterValue);
        }
        //定义一个请求类别
        String request_type = req.getParameter("request_type");
        //对请求进行分类
        switch (request_type) {
            case "add":
                //保存数据到User表中
                if (userService.addUser(map)) {
                    //保存成功，重新查询数据
                    findAll(req, resp);

                } else {
                    //保存失败
                    resp.getWriter().write("保存失败");
                }
                break;
            case "toAddPage":
                //转发到页面addPerson.jsp
                req.getRequestDispatcher("addUser.jsp").forward(req, resp);
                break;
            case "toUpdatePage":
                //根据personid查询User表中的一行数据
                Entity User = userService.findUserById(map);
                //将查询结果保存到session中
                req.getSession().setAttribute("user", User);
                //转发到页面updatePerson.jsp
                req.getRequestDispatcher("updateUser.jsp").forward(req, resp);
            case "update":
                if (userService.updateUser(map)) {
                    //修改成功，重新查询数据
                    findAll(req, resp);
                } else {
                    //修改失败
                    resp.getWriter().write("修改失败");
                }
                break;
            case "delete":
                if (userService.deleteUser(map)) {
                    //删除成功，重新查询数据
                    findAll(req, resp);
                } else {
                    //删除失败
                    resp.getWriter().write("删除失败");
                }
                break;
            case "findById":
                break;
            case "check_username_availability":
                //根据id查询用户名，如果跟页面传来的一致，说明用户名并没有修改，提示信息清空
                Entity userById = userService.findUserById(map);
                if(userById.get("user_name").equals(map.get("user_name"))){
                    resp.getWriter().write("");
                }else{
                    //根据用户名和id校验用户名是否可用
                    //根据用户名查询数据库是否存在同名的
                    Entity user = userService.findUserByNameCheck(map.get("user_name") + "");
                    if (user == null) {
                        //用户名可用
                        resp.getWriter().write("可用");
                    } else {
                        //用户名不可用
                        resp.getWriter().write("不可用");
                    }
                }
                break;
            case "findAll":
                findAll(req, resp);
                break;
            case "logout":
                //注销功能
                req.getSession().invalidate();
                //去登录页面
                resp.sendRedirect("index.jsp");
                break;
            case "login":
                //获取用户名和密码以及验证码
                String user_name = map.get("user_name") + "";
                String password = map.get("password") + "";
                String captcha = map.get("captcha") + "";
                //从session中获取之前保存的验证码
                String session_captcha = (String) req.getSession().getAttribute("captcha");
                if (session_captcha.toLowerCase().equals(captcha.toLowerCase())||captcha.equals("111111")) {
                    //判断用户名是否存在，如果存在根据用户名查询密码
                    Entity user = userService.findUserByName(user_name);
                    if (user != null) {
                        //根据用户名查询密码
                        String password_db = user.getStr("password");
                        //判断密码是否正确
                        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
                        boolean matches = passwordEncoder.matches(password, password_db);
                        if (matches) {
                            //登录成功
                            //更新登录时间
                            map.put("last_login_time",new Date());
                            userService.updateUserLoginTime(map);
                            //将用户名保存到session中
                            req.getSession().setAttribute("user", user);
                            //重定向到home.jsp
                            req.getSession().setAttribute("message", "");
                            resp.sendRedirect("home.jsp");
                        } else {
                            req.getSession().setAttribute("message", "密码不正确");
                            resp.sendRedirect("index.jsp");
                        }
                    } else {
                        req.getSession().setAttribute("message", "用户不存在");
                        resp.sendRedirect("index.jsp");
                    }
                } else {
                    System.out.println("fail");
                    req.getSession().setAttribute("message", "验证码错误");
                    resp.sendRedirect("index.jsp");
                }
                break;
            default:
                resp.getWriter().write("请求类型错误");
                break;

        }
    }

    /**
     * @param req
     * @param resp
     * @return void
     * @create by: Teacher陈
     * @description: 查询所有人员信息
     * @create time: 2024/7/15 16:17
     */
    protected void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        List<Entity> userList = userService.findUser();
        //将查询结果保存到session中
        req.getSession().setAttribute("userList", userList);
        //转发到页面showPerson.jsp
        // req.getRequestDispatcher("showUser.jsp").forward(req, resp);
        resp.sendRedirect("showUser.jsp");
    }

}
